package com.youhome.service.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSSClient;
import com.youhome.common.config.OSSConfig;
import com.youhome.service.response.TimeValueItemResult;
import com.youhome.service.service.DownloadService;
import com.youhome.service.service.OSSService;
import com.youhome.utils.DateFormatUtils;
import com.youhome.utils.DateUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;

/**
 * Created by chen365 on 2017/11/8.
 */
@Service
public class DownloadServiceImpl implements DownloadService {
    @Autowired
    public OSSConfig ossConfig;
    @Autowired
    private OSSService ossService;

    @Override
    public String downloadExcel(String filename) throws Exception {
        System.err.println("filename:" + filename);
        if (ossService.exist(
                ossConfig.getEndpoint(),
                ossConfig.getAccessKeyId(),
                ossConfig.getAccessKeySecret(),
                ossConfig.getBacketName(),
                filename)) {
            Long time = Long.valueOf(1800 * 1000);
            String downloadUrl = ossService.createTemporaryUrl(ossConfig, filename, time);
            System.err.println("downloadUrl:" + downloadUrl);
            if (!StringUtils.isEmpty(downloadUrl)) {
                return downloadUrl;
            } else {
                return null;
            }
        } else {
            System.err.println("oss不存在文件：" + filename);
            return null;
        }
    }

    @Override
    public String downloadJsonFromOSS(String key) {
        OSSClient ossClient = new OSSClient(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
        return ossService.downloadJson(ossClient, ossConfig.getBacketName(), key);
    }

    @Override
    public List<TimeValueItemResult> downloadTimeValuesFromOSS(String key) {
        OSSClient ossClient = new OSSClient(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
        String json = null;
        try {
            json = ossService.downloadJson(ossClient, ossConfig.getBacketName(), key);
        } catch (Exception e) {
            System.err.println("==============downloadJson  Exception==================");
            e.printStackTrace();
        }
        //System.err.println(key);
        //System.err.println(json);
        if (!StringUtils.isEmpty(json)) {
            JSONObject jsonObject = JSON.parseObject(json);
            String times = jsonObject.getString("time");
            //System.err.println(times);
            List<TimeValueItemResult> lists = JSONArray.parseArray(times, TimeValueItemResult.class);
            if (lists != null) {
                Collections.sort(lists, new Comparator<TimeValueItemResult>() {
                    public int compare(TimeValueItemResult p1, TimeValueItemResult p2) {
                        //按照 TimeValueItemResult 的 time 进行升序排列
                        Date time1 = DateUtils.StrToDate(p1.getTime(), "yyyy-MM");
                        Date time2 = DateUtils.StrToDate(p2.getTime(), "yyyy-MM");
                        return time1.compareTo(time2); //升序
                        //return time2.compareTo(time1); // 降序
                    }
                });
            }
            return lists;
        }
        return null;
    }

    @Override
    public List<TimeValueItemResult> downloadTimeValuesFromOSS(String key, String time) {
        String dateFormat = "yyyy-MM";
        Date etime = new Date();
        Date btime = DateUtils.addYear(etime, -Integer.parseInt(time));

        //System.err.println(DateUtils.formatDate(btime, dateFormat) + "--" + DateUtils.formatDate(etime, dateFormat));
        //http://youhome.oss-cn-zhangjiakou.aliyuncs.com/zillow/Zip_Zri_AllHomesPlusMultifamily/02072.json
        //String key = "zillow/Zip_Zri_AllHomesPlusMultifamily/" + zipcode + ".json";
        List<TimeValueItemResult> timeValueItemResults = downloadTimeValuesFromOSS(key);

        //如果没有数据返回空
        if (timeValueItemResults == null) {
            return null;
        }

        //是否需要截取 time = 0 ,返回所有数据
        if (time.equals("0")) {
            return timeValueItemResults;
        }
        //开始截取的时间
        String startTime = DateFormatUtils.format(btime, dateFormat);
        //如果要截取的时间不在数据范围内则返回所有数据
        String minTime = timeValueItemResults.get(0).getTime();
        if (startTime.compareTo(minTime) == -1) {
            //截取的开始时间大过数据的开始时间
            return timeValueItemResults;
        }

        //按时间截取数据
        List<TimeValueItemResult> items = new ArrayList<>();
        Boolean flag = false; // 开始截取标识
        for (TimeValueItemResult timeValueItemResult : timeValueItemResults) {
            if (timeValueItemResult.getTime().equalsIgnoreCase(startTime)) {
                flag = true;  //从这个开始截取
            }
            if (flag) {
                items.add(timeValueItemResult);
            }
        }
        return items;
    }

    @Override
    public String downloadFromGoogleStaticMap(String path) {
        if (path.isEmpty())
            path = "https://maps.google.cn/maps/api/staticmap?center=40.7520027161,-74.002166748&visible=40.7520027161,-74.002166748&zoom=16&size=640x640&key=AIzaSyDH6NBqY397pB_dQfDyb4jLwVD73FeOELU";
        URL url = null;
        Boolean flag = false;
        try {
            url = new URL(path);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        InputStream inputStream = null;
        String fileNme = "/google_static_map/" + UUID.randomUUID().toString() + ".png";
        String save = "/alldata" + fileNme;
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        OutputStream out = null;
        try {
            inputStream = url.openStream();
            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) > 0) {
                outStream.write(buffer, 0, length);
            }
            byte[] data = outStream.toByteArray();
            // 输出的文件流保存图片至本地
            out = new FileOutputStream(new File(save));
            out.write(data);
            out.flush();
            flag = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outStream != null) {
                try {
                    outStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        if (flag) {
            return fileNme;
        } else {
            return null;
        }
    }

}
